#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/epoll.h>
#include "common.hpp"
#include "Log.hpp"

using namespace LogMoudle;
namespace EpollMoudle
{
class Epoller
{
    public:
    Epoller(int eofd=-1)
    :_eofd(eofd)
    {
        _eofd=epoll_create(128);
        if(_eofd<0)
        {
            LOG(loglevel::FATAL)<< "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(loglevel::INFO)<< "create epoll success: " << _eofd ;
    }
    void  ModEventHelper(int sockfd,uint32_t events,int oper)
    {
        struct epoll_event as;
        as.events=events;
        as.data.fd=sockfd;
        int n=epoll_ctl(_eofd,oper,sockfd,&as);
        if(n<0)
        {
            LOG(loglevel::FATAL)<<"epoll_ctl error";
            return;
        }
        LOG(loglevel::INFO) << "epoll_ctl success: " << sockfd;

    }
    void AddEvent(int sockfd,uint32_t events)//添加文件描述符以及对应的事件
    {
       ModEventHelper(sockfd,events,EPOLL_CTL_ADD);
    }
    void DelEvent(int sockfd)
    {
        int n=epoll_ctl(sockfd,EPOLL_CTL_DEL,sockfd,nullptr);
        (void)n;
    }
    void ModEvent(int sockfd,uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_MOD);
    }
    int WaitEvents(struct epoll_event revs[],int maxnum,int timeout)
    {
        int n=epoll_wait(_eofd,revs,maxnum,timeout);
        if(n<0)
        {
            LOG(loglevel::WARNING)<<"epoll_wait error";
        }
        else if(n==0)
        {
            LOG(loglevel::WARNING)<<"epoll_wait timeout";
        }
        else
        {
            //todo
        }
        return n;
    }
    ~Epoller()
    {
        if(_eofd>=0)
        {
            close(_eofd);
        }
    }
    private:
    int _eofd;
};
}